using System;
using System.IO;
using MongoDB.Driver.GridFS;

namespace MongoScienceDAL.Core
{
    public class ScienceFileRepository : IScienceFileRepository
    {
        private readonly MongoGridFS _mongoGridFS;

        public ScienceFileRepository(IDataSource dataSource)
        {
            _mongoGridFS = dataSource.Database.GridFS;
        }

        public ScienceFile Upload(Stream fileStream, string filename, string uploader)
        {
            var fileInfo = _mongoGridFS.Upload(fileStream, filename);

            return new ScienceFile
            {
                FileId = fileInfo.Id.AsObjectId,
                Filename = filename,
                Size = fileInfo.Length,
                UploadedBy = uploader,
                UploadedOn = DateTime.Now
            };
        }

        public Stream Download(ScienceFile file)
        {
            var fileInfo = _mongoGridFS.FindOneById(file.FileId);
            return fileInfo.OpenRead(); 
        }

        public void Delete(ScienceFile file)
        {
            _mongoGridFS.DeleteById(file.FileId);
        }
    }
}